﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FanPages.Server.Services.Contracts;
using FanPages.Server.Services;
using FanPages.Model;
using FanPages.Client.Core.Transformers;

namespace FanPagesWeb.Controllers
{
    public class ConfigurationController : Controller
    {
        IConfigurationService service = new ConfigurationService();

        public ActionResult Index()
        {
            var fanItem = Session["FanItem"] as FanItem;
            var config = service.GetByFanItem(new FanItemTransformer().ToDto(fanItem));
            if (config != null)
            {
                return View("Edit", new ConfigurationTransformer().ToClient(config));
                
            }
            else
            {
                var newConfig = new Configuration()
                {
                    FanItem = fanItem,
                    SearchWords = String.Empty
                };
                service.Save(new ConfigurationTransformer().ToDto(newConfig));
                config = service.GetByFanItem(new FanItemTransformer().ToDto(fanItem));
                return View("Edit", new ConfigurationTransformer().ToClient(config));
            }
        }        

        public ActionResult Edit(int id)
        {
            var config = service.GetById(id);
            return View(new ConfigurationTransformer().ToClient(config));
        }

        [HttpPost]
        public ActionResult Edit(int id, Configuration config)
        {
            try
            {
                var fanItem = Session["FanItem"] as FanItem;
                config.FanItem = fanItem;
                service.Save(new ConfigurationTransformer().ToDto(config));
                return RedirectToAction("Index", "FanItem");
            }
            catch
            {
                return View();
            }
        }        
    }
}
